package com.cr.crandroid.ui.person.user;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.navigation.Navigation;

import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.cr.crandroid.R;
import com.cr.crandroid.base.BaseFragment2;
import com.cr.crandroid.model.LoginModel;
import com.cr.crandroid.utils.CommonConstant;
import com.cr.crandroid.utils.OConvertUtils;
import com.cr.crandroid.utils.OkHttpManager;
import com.google.android.material.snackbar.Snackbar;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;


public class LoginFragment extends BaseFragment2 {


    private EditText editText;
    private EditText editText2;
    private SharedPreferences loginSharedPreferences;
    private Integer navigateAction = -1;
    private Bundle arguments;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View root = inflater.inflate(R.layout.fragment_login, container, false);
        editText = root.findViewById(R.id.editText);
        editText2 = root.findViewById(R.id.editText2);
        TextView textView = root.findViewById(R.id.textView);
        loginSharedPreferences = getActivity().getSharedPreferences("login", Context.MODE_PRIVATE);
        String username = loginSharedPreferences.getString("username", "");
        String password = loginSharedPreferences.getString("password", "");
        editText.setText(username);
        editText2.setText(password);
        textView.setOnClickListener(view -> Navigation.findNavController(view)
                .navigate(R.id.action_loginFragment_to_registerFragment));
//        TextView textView2 = root.findViewById(R.id.textView2);
//        textView2.setOnClickListener(view -> Navigation.findNavController(view)
//                .navigate(R.id.action_loginFragment_to_findPasswordFragment));
        Bundle arguments = getArguments();
        if (arguments != null && arguments.containsKey("jump")) {
            navigateAction = Integer.parseInt(arguments.getString("jump"));
        }
        Button button = root.findViewById(R.id.button);
        button.setOnClickListener(this::login);
        return root;
    }

    /**
     * 账号密码登录
     *
     * @param view
     */
    private void login(final View view) {
        String name = editText.getText().toString();
        String password = editText2.getText().toString();
        if (TextUtils.isEmpty(name)) {
            editText.setError("账号不能为空");
            return;
        }
        if (TextUtils.isEmpty(password)) {
            editText2.setError("密码不能为空");
            return;
        }
        final LoginModel loginUser = new LoginModel();
        //此处替换为你的用户名
        loginUser.setUsername(name);
        //此处替换为你的密码
        loginUser.setPassword(password);
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    OkHttpManager.postJ(CommonConstant.URL + "/login", new Gson().toJson(loginUser), new Callback() {
                        @Override
                        public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                            String res = response.body().string();
                            JsonObject result = JsonParser.parseString(res).getAsJsonObject();
                            if (Integer.parseInt(String.valueOf(result.get("code"))) != CommonConstant.ERROR) {
                                LoginViewModel.user = JsonParser.parseString(String.valueOf(result.get("result"))).getAsJsonObject();
                                getActivity().runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        if (LoginViewModel.user.has("id")) {
                                            SharedPreferences.Editor editor = loginSharedPreferences.edit();
                                            editor.putString("username", OConvertUtils.getString(LoginViewModel.user.get("username").toString()));
                                            editor.putString("password", password);
                                            editor.apply();
                                            Snackbar.make(view, "登录成功!",
                                                    Snackbar.LENGTH_LONG).show();
                                            if (navigateAction == -1)
                                                Navigation.findNavController(view).popBackStack();
                                            else {
                                                Bundle bundle = new Bundle();
                                                bundle.putString("action", String.valueOf(navigateAction));
                                                Navigation.findNavController(view).navigate(R.id.action_loginFragment_to_navigation_person, bundle);
                                            }

                                        }
                                    }
                                });
                            } else {
                                Snackbar.make(view, result.get("message") + "",
                                        Snackbar.LENGTH_LONG).show();
                            }

                        }

                        @Override
                        public void onFailure(@NonNull Call call, @NonNull IOException e) {

                        }
                    });
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        }).start();

    }
}